﻿//************************************************************************************************
// Copyright © 2014 Steven M. Cohn. All Rights Reserved.
// 
//************************************************************************************************

namespace River.Folderize.UI
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.IO;
	using System.Linq;
	using System.Windows;
	using System.Windows.Controls;
	using System.Windows.Input;


	/// <summary>
	/// Interaction logic for FolderPanel.xaml
	/// </summary>

	public partial class FolderPanel : UserControl
	{

		private FolderController controller;
		private List<Folder> folders;


		/// <summary>
		/// 
		/// </summary>

		public FolderPanel ()
		{
			InitializeComponent();

			controller = new FolderController();
			folders = controller.GetFolders();

			if (!DesignerProperties.GetIsInDesignMode(this))
			{
				SetupSystemFolders(controller, folders);
				SetupCustomFolders(folders);
			}
		}


		#region Setup

		private void SetupSystemFolders (FolderController controller, List<Folder> folders)
		{
			Folder folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.DesktopID))
				?? controller.Lookup<SystemFolder>(FolderController.DesktopID);

			this.desFolder.DataContext = folder;
			this.desFolder.Tag = folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.DownloadsID))
				?? controller.Lookup<SystemFolder>(FolderController.DownloadsID);

			this.dowFolder.DataContext = folder;
			this.dowFolder.Tag = folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.DocumentsID))
				?? controller.Lookup<SystemFolder>(FolderController.DocumentsID);

			this.docFolder.DataContext = folder;
			this.docFolder.Tag = folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.MusicID))
				?? controller.Lookup<SystemFolder>(FolderController.MusicID);

			this.musFolder.DataContext = folder;
			this.musFolder.Tag = folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.PicturesID))
				?? controller.Lookup<SystemFolder>(FolderController.PicturesID);

			this.picFolder.DataContext = folder;
			this.picFolder.Tag = folder;

			folder = folders.SingleOrDefault(p => p.Guid.Equals(FolderController.VideosID))
				?? controller.Lookup<SystemFolder>(FolderController.VideosID);

			this.vidFolder.DataContext = folder;
			this.vidFolder.Tag = folder;

			this.customFoldersList.Items.SortDescriptions.Add(
				new SortDescription("Name", ListSortDirection.Ascending));

			folder = controller.Lookup<SpecialFolder>(FolderController.OneDriveID);
			if (folder.Guid != null)
			{
				topOneDriveMenu.DataContext = folder;
			}
			else
			{
				topOneDriveMenu.IsEnabled = false;
			}

			folder = controller.Lookup<SpecialFolder>(FolderController.UserLibrariesID);
			if (folder.Guid != null)
			{
				topLibrariesMenu.DataContext = folder;
			}
			else
			{
				topLibrariesMenu.IsEnabled = false;
			}
		}


		private void SetupCustomFolders (List<Folder> folders)
		{
			foreach (Folder folder in folders)
			{
				if (!folder.IsSystemFolder)
				{
					customFoldersList.Items.Add(folder);

					if (folder.Name == "Libraries")
					{
						libraryButton.IsEnabled = false;
					}
				}
			}

			// TODO: should use binding instead
			customFoldersList.Items.Refresh();
		}

		#endregion Setup



		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// System Folder functions
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

		private void IncludeSystemFolder (object sender, RoutedEventArgs e)
		{
			if (!this.IsLoaded)
				return;

			var folder = ((FolderSelectorControl)sender).Tag as Folder;
			if (folder != null)
			{
				controller.IncludeSystemFolder(folder.Guid);
			}
		}


		private void ExcludeSystemFolder (object sender, RoutedEventArgs e)
		{
			if (!this.IsLoaded)
				return;

			var folder = ((FolderSelectorControl)sender).Tag as Folder;
			if (folder != null)
			{
				controller.ExcludeSystemFolder(folder.Guid);
			}
		}


		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
		// Custom Folder functions
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

		private void AddCustomFolder (object sender, RoutedEventArgs e)
		{
			var folder = new CustomFolder(Guid.NewGuid().ToString("B"));
			editor.Create(folder);
		}


		private void PropertiesCompleted (object sender, PropertiesEditedRoutedEventArgs e)
		{
			var folder = e.Folder as CustomFolder;

			if (e.IsNewFolder)
			{
				if (Directory.Exists(folder.Path))
				{
					// check if custom folder already exists for given path
					var owner = folders.SingleOrDefault(p => p.Path.Equals(folder.Path));
					if (owner != null)
					{
						MessageBox.Show(Application.Current.MainWindow,
							"You already have a custom folder for this path",
							"Duplicate", MessageBoxButton.OK, MessageBoxImage.Information);
					}
					else
					{
						controller.AddCustomFolder(folder);
						folders.Add(folder);

						customFoldersList.Items.Add(folder);
					}
				}
			}
			else
			{
				controller.SaveProperties(folder);
			}

			customFoldersList.Items.Refresh();
		}


		private void AddLibraryFolder (object sender, RoutedEventArgs e)
		{
			var folder = controller.AddLibrariesFolder();
			// TODO: should use binding instead
			customFoldersList.Items.Add(folder);
			customFoldersList.Items.Refresh();
			folders.Add(folder);
			libraryButton.IsEnabled = false;
		}


		private void EditItem (object sender, MouseButtonEventArgs e)
		{
			if (e.ClickCount >= 2)
			{
				EditProperties(sender, e);
			}
		}


		private void EditProperties (object sender, RoutedEventArgs e)
		{
			var folder = customFoldersList.SelectedItem as CustomFolder;
			if ((folder.Image == null) && !String.IsNullOrEmpty(folder.ImageRes))
			{
				folder.Image = ImageHelper.LoadIcon(folder.ImageRes, ImageHelper.ImageType.Folder);
			}

			editor.Modify(folder);
		}


		private void RemoveCustomFolder (object sender, RoutedEventArgs e)
		{
			var folder = customFoldersList.SelectedItem as Folder;
			if (folder != null)
			{
				var result = MessageBox.Show(Application.Current.MainWindow,
					"Remove folder " + folder.Name + "?",
					"Confirm", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);

				if (result == MessageBoxResult.Yes)
				{
					controller.RemoveCustomFolder(folder.Guid);
					customFoldersList.Items.Remove(customFoldersList.SelectedItem);

					if (folder.Name == "Libraries")
					{
						libraryButton.IsEnabled = true;
					}

					folders.RemoveAll(p => p.Guid.Equals(folder.Guid));
				}
			}
		}


		private void SelectionChanged (object sender, SelectionChangedEventArgs e)
		{
			if (customFoldersList.SelectedIndex == -1)
			{
				removeButton.IsEnabled = false;
				iconButton.IsEnabled = false;
				pinButton.IsEnabled = false;
			}
			else
			{
				var folder = customFoldersList.SelectedItem as Folder;
				removeButton.IsEnabled = true;
				iconButton.IsEnabled = true;
				pinButton.IsEnabled = true;
				pinButton.IsChecked = controller.IsPinned(folder.Guid);
				pathLabel.Content = folder.Path;
			}
		}


		private void SetFolderSortOrder (object sender, RoutedEventArgs e)
		{
			if (!this.IsLoaded)
				return;

			string tag = ((MenuItem)sender).Tag as string;
			if (tag.Equals("OneDrive") || tag.Equals("UserLibraries"))
			{
				var folder = ((MenuItem)sender).DataContext as SpecialFolder;
				int index = controller.SetSortOrderIndex(folder.Guid, !folder.AtTop);
				if (index >= 0)
				{
					folder.SortOrderIndex = index;
				}
				else
				{
					((MenuItem)sender).IsChecked = folder.AtTop;

					MessageBox.Show("Unable to change item", "Error",
						MessageBoxButton.OK, MessageBoxImage.Error);
				}
			}
		}


		private void TogglePinned (object sender, RoutedEventArgs e)
		{
			var folder = customFoldersList.SelectedItem as Folder;
			if (folder != null)
			{
				if (controller.IsPinned(folder.Guid))
				{
					controller.Unpin(folder.Guid);
				}
				else
				{
					controller.Pin(folder.Guid);
				}
			}
		}
	}
}
